<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧用户信息 -->
      <el-col :span="8">
        <el-card class="user-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" @click="editMode = true" v-if="!editMode">
                编辑
              </el-button>
            </div>
          </template>
          
          <!-- 添加头像显示和上传 -->
          <div class="avatar-container">
            <el-avatar 
              :size="100" 
              :src="userForm.avatar || '/default-avatar.png'"
              @error="() => true"
            >
              {{ userForm.username?.charAt(0)?.toUpperCase() }}
            </el-avatar>
            <el-upload
              v-if="editMode"
              class="avatar-uploader"
              :action="`${baseURL}/api/upload`"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>

          <el-form 
            :model="userForm" 
            :rules="rules"
            ref="userFormRef"
            :disabled="!editMode"
          >
            <el-form-item prop="username" label="用户名">
              <el-input v-model="userForm.username" />
            </el-form-item>
            
            <el-form-item prop="phone" label="手机号">
              <el-input v-model="userForm.phone" />
            </el-form-item>
            
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="userForm.email" />
            </el-form-item>

            <!-- 添加积分显示 -->
            <el-form-item label="我的积分">
              <div class="points-display">
                <el-tag type="success" size="large">{{ userForm.points || 0 }} 分</el-tag>
              </div>
            </el-form-item>

            <el-form-item v-if="editMode">
              <el-button type="primary" @click="handleSaveUserInfo">
                保存
              </el-button>
              <el-button @click="editMode = false">
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧偏好设置 -->
      <el-col :span="16">
        <el-card class="preference-card">
          <template #header>
            <div class="card-header">
              <span>偏好设置</span>
            </div>
          </template>

          <el-form :model="preferenceForm" label-width="100px">
            <el-form-item label="喜好分类">
              <el-select
                v-model="preferenceForm.fav_categories"
                multiple
                placeholder="选择喜好的菜品分类"
              >
                <el-option
                  v-for="category in categories"
                  :key="category"
                  :label="category"
                  :value="category"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="口味标签">
              <el-select
                v-model="preferenceForm.fav_tags"
                multiple
                placeholder="选择喜好的口味标签"
              >
                <el-option
                  v-for="tag in tags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="辣度偏好">
              <el-rate
                v-model="preferenceForm.spicy_level"
                :max="3"
                :texts="['不辣', '微辣', '中辣', '重辣']"
                show-text
              />
            </el-form-item>

            <el-form-item label="饮食需求">
              <el-checkbox-group v-model="preferenceForm.dietary_needs">
                <el-checkbox label="无糖">无糖</el-checkbox>
                <el-checkbox label="低脂">低脂</el-checkbox>
                <el-checkbox label="素食">素食</el-checkbox>
                <el-checkbox label="清淡">清淡</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="过敏原">
              <el-select
                v-model="preferenceForm.allergies"
                multiple
                placeholder="选择需要避免的食材"
              >
                <el-option
                  v-for="allergy in allergies"
                  :key="allergy"
                  :label="allergy"
                  :value="allergy"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="不喜欢的菜品">
              <el-select
                v-model="preferenceForm.disliked_dishes"
                multiple
                placeholder="选择不喜欢的菜品"
                filterable
              >
                <el-option
                  v-for="dish in allDishes"
                  :key="dish.ID"
                  :label="dish.name"
                  :value="dish.ID"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSavePreferences">
                保存偏好设置
              </el-button>
            </el-form-item>
          </el-form>

          <div class="favorites-section">
            <h3>收藏的菜品</h3>
            <el-table :data="favorites" style="width: 100%">
              <el-table-column prop="name" label="菜品名称" />
              <el-table-column prop="price" label="价格">
                <template #default="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="category" label="分类" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    size="small"
                    @click="handleRemoveFavorite(scope.row)"
                  >
                    取消收藏
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 添加分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="total"
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'

interface UserForm {
  username: string
  phone: string
  email: string
  avatar: string
  points: number
}

interface PreferenceForm {
  fav_categories: string[]
  fav_tags: string[]
  spicy_level: number
  dietary_needs: string[]
  allergies: string[]
  disliked_dishes: number[]
}

interface FavoriteDish {
  ID: number
  name: string
  price: number
  category: string
}

interface Dish {
  ID: number
  name: string
}

const store = useStore()
const userFormRef = ref<FormInstance>()
const editMode = ref(false)

const userForm = ref<UserForm>({
  username: '',
  phone: '',
  email: '',
  avatar: '',
  points: 0
})

const preferenceForm = reactive<PreferenceForm>({
  fav_categories: [],
  fav_tags: [],
  spicy_level: 0,
  dietary_needs: [],
  allergies: [],
  disliked_dishes: []
})

const categories = ref(['川菜', '粤菜', '湘菜', '东北菜'])
const tags = ref(['辣', '酸', '甜', '咸', '鲜'])
const favorites = ref<FavoriteDish[]>([])
const allDishes = ref<Dish[]>([])
const allergies = ref(['花生', '海鲜', '蛋类', '乳制品', '坚果'])

const baseURL = 'http://localhost:8080'
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${store.state.token}`
}))

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const currentUser = store.state.user
    console.log('Current user from store:', currentUser)
    
    if (!currentUser?.id) {
      ElMessage.error('用户信息不存在')
      return
    }

    const response = await fetch(`http://localhost:8080/api/users/${currentUser.id}`, {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    console.log('User data from API:', data)
    
    if (response.ok) {
      Object.assign(userForm.value, {
        username: data.user.Username,
        phone: data.user.Phone,
        email: data.user.Email,
        avatar: data.user.Avatar,
        points: data.user.Points
      })
    } else {
      ElMessage.error(data.message || '加载用户信息失败')
    }
  } catch (error) {
    console.error('Load user info error:', error)
    ElMessage.error('加载用户信息失败')
  }
}

// 加载偏好设置
const loadPreferences = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/preferences', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    console.log('Preference data from API:', data)
    if (response.ok) {
      preferenceForm.fav_categories = data.preference.FavCategories || []
      preferenceForm.fav_tags = data.preference.FavTags || []
      preferenceForm.spicy_level = data.preference.SpicyLevel || 0
      preferenceForm.dietary_needs = data.preference.DietaryNeeds || []
      preferenceForm.allergies = data.preference.Allergies || []
      preferenceForm.disliked_dishes = data.preference.DislikedDishes || []
    }
  } catch (error) {
    console.error('Load preferences error:', error)
    ElMessage.error('加载偏好设置失败')
  }
}

// 加载收藏的菜品
const loadFavorites = async () => {
  try {
    const response = await fetch(
      `http://localhost:8080/api/favorites/dishes?page=${currentPage.value}&pageSize=${pageSize.value}`, 
      {
        headers: {
          'Authorization': `Bearer ${store.state.token}`
        }
      }
    )
    const data = await response.json()
    console.log('Favorites data from API:', data)
    if (response.ok) {
      favorites.value = data.favorites.map((fav: any) => ({
        ID: fav.Dish.ID,
        name: fav.Dish.name,
        price: fav.Dish.price,
        category: fav.Dish.Category
      }))
      total.value = data.total
    }
  } catch (error) {
    console.error('Load favorites error:', error)
    ElMessage.error('加载收藏菜品失败')
  }
}

// 加载所有菜品列表
const loadAllDishes = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/dishes', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      allDishes.value = data.dishes
    }
  } catch (error) {
    console.error('Load dishes error:', error)
    ElMessage.error('加载菜品列表失败')
  }
}

// 保存用户信息
const handleSaveUserInfo = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const currentUser = store.state.user
        if (!currentUser?.ID) {
          ElMessage.error('用户信息不存在')
          return
        }

        const response = await fetch(`http://localhost:8080/api/users/${currentUser.ID}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            username: userForm.value.username,
            phone: userForm.value.phone,
            email: userForm.value.email,
            avatar: userForm.value.avatar
          })
        })

        const data = await response.json()
        
        if (response.ok) {
          ElMessage.success('保存成功')
          editMode.value = false
          // 更新 store 中的用户信息
          store.commit('setUserInfo', data.user)
        } else {
          ElMessage.error(data.message || '保存失败')
        }
      } catch (error) {
        console.error('Save user info error:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 保存偏好设置
const handleSavePreferences = async () => {
  try {
    console.log('Sending preference data:', preferenceForm)
    const response = await fetch('http://localhost:8080/api/preferences', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(preferenceForm)
    })
    const data = await response.json()
    console.log('Response from server:', data)
    if (response.ok) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(data.error || '保存失败')
    }
  } catch (error) {
    console.error('Save preferences error:', error)
    ElMessage.error('保存失败')
  }
}

// 取消收藏
const handleRemoveFavorite = async (dish: FavoriteDish) => {
  try {
    const response = await fetch(`http://localhost:8080/api/favorites/dishes/${dish.ID}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    if (response.ok) {
      ElMessage.success('已取消收藏')
      loadFavorites()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理头像上传
const handleAvatarSuccess = (response: any) => {
  userForm.value.avatar = baseURL + response.url  // response.url 已经包含了 /uploads/images/ 路径
  // 立即更新用户信息
  handleSaveUserInfo()
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadFavorites()
}

// 处理每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  loadFavorites()
}

onMounted(() => {
  loadUserInfo()
  loadPreferences()
  loadFavorites()
  loadAllDishes()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.avatar-container {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  margin-top: 10px;
}

.points-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-card {
  margin-bottom: 20px;
}

.preference-card {
  margin-bottom: 20px;
}

.favorites-section {
  margin-top: 20px;
}

:deep(.el-rate__text) {
  margin-left: 10px;
  font-size: 14px;
}

:deep(.el-select) {
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 